require 'fileutils'
require 'rubygems'
require 'rake/testtask'
require 'ftools'
require 'database'
include FileUtils

task :default => :test

desc "Run tests"
task :test => :dbinit do |t|
  Rake::TestTask.new do |t|
    t.test_files = FileList['test/*test*.rb']
    t.verbose = true
  end
end

desc "create the db schema"
task :dbinit do |t|
  Database.test_connect
end

desc "create a .deb of the project"
task :build_deb => :create_tmp do |t|
  tmp = tmp_dir
  `tar czf #{tmp}.tar.gz #{tmp}`
end

desc "delete temporary build files"
task :clean do |t|
  FileList['cfgmgr*'].each{|file| rm_rf(file)}
end

desc "create a temporary build location"
task :create_tmp => :clean do |t|
  to_copy = Dir.entries('.').delete_if{|item| /^\./.match(item)}
  tmp = tmp_dir
  mkdir(tmp)
  to_copy.each{|item| cp_r(item, tmp)}
end

desc "install the application so that the binary is in bin and libraries are in lib"
task :install => :create_tmp do |t|
  mkdir(ENV['bin']) if !File.exists?(ENV['bin'])
  mkdir(ENV['lib']) if !File.exists?(ENV['lib'])
  tmp = tmp_dir
  libs = FileList["#{tmp}/*.rb"]
  libs.each{|item| cp_r(item, ENV['lib'])}
  cp_r('config-manager', ENV['bin'])
  add_lib_to_binary_path
end

def tmp_dir
  revision = /Revision: (.*)/.match(`svn info`)[1].to_i
  "cfgmgr-0.#{revision}"
end

def add_lib_to_binary_path
  content = nil
  File.open("#{ENV['bin']}/config-manager") { |f| content = f.readlines }
  content.unshift(content[0])
  content[1] = "$: << '#{File.expand_path(ENV['lib'])}'"
  File.open("#{ENV['bin']}/config-manager", "w"){ |f| content.each{|line| f.puts(line)}}
end
